.pc = * "Level routines"

/////////////////////////////

.label map_width = $8000
.label map_height = $8001
.label map_num_triggers = $8002
.label map_triggers = $8003
.label map_enter = $8005
.label map_exit = $8008
.label map_data = $800b

//////////////////////////////

load_new_level:
{
.label ptr = zero_page_start // two bytes
.label ptr2 = zero_page_start+2

    // save XY
    txa
    pha
    tya
    pha

    // exit current level
    jsr map_exit

    // restore XY
    pla
    tay
    pla
    tax

    // blank the whole screen
    lda $d011
    and #[255-16]
    sta $d011
    
    stx ptr
    sty ptr+1

    lda #<hero_pos_x
    sta ptr2
    lda #>hero_pos_x
    sta ptr2+1

    // copy new hero position
    ldy #0
loop:
    lda (ptr),y
    sta (ptr2),y
    iny
    cpy #4
    bne loop

    // copy new origin
    lda (ptr),y
    sta background_origin_x
    iny
    lda (ptr),y
    sta background_origin_y
    lda #0
    sta background_origin_x_half
    sta background_origin_y_half
    
    // increment pointer by 6 and call load_file
    lda ptr
    clc
    adc #6
    tax
    lda ptr+1
    adc #0
    tay
    jsr load_file

    // set up new level
    jsr map_lookup_init
    jsr background_full_update
    
    // force stack to the right depth
    ldx stack_base
    txs

    // unblank the screen
    lda $d011
    ora #16
    sta $d011

    // enter new level
    jsr map_enter

    // go right into main loop
    jmp main_loop
}

level_check_triggers:
{
.label trigger_ptr = zero_page_start // two bytes
.label count = zero_page_start+2

    lda map_triggers
    sta trigger_ptr
    lda map_triggers+1
    sta trigger_ptr+1

    ldx map_num_triggers
    stx count
    
loop:
    ldx count
    beq done
    dex
    stx count

    // test lower x
    ldy #0
    lda hero_pos_x+1
    cmp (trigger_ptr),y
    bcc next_trigger

    // test lower y
    iny
    lda hero_pos_y+1
    cmp (trigger_ptr),y
    bcc next_trigger

    // test upper x
    iny
    lda (trigger_ptr),y
    cmp hero_pos_x+1
    bcc next_trigger
    
    // test upper y
    iny
    lda (trigger_ptr),y
    cmp hero_pos_y+1
    bcc next_trigger

    // call the trigger function
    lda trigger_ptr
    clc
    adc #4
    sta jsr_instr+1
    lda trigger_ptr+1
    adc #0
    sta jsr_instr+2
jsr_instr:
    jsr $ffff

next_trigger:
    lda trigger_ptr
    clc
    adc #7
    sta trigger_ptr
    lda trigger_ptr+1
    adc #0
    sta trigger_ptr+1
    jmp loop

done:
    rts
}
